import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
} from '@fast-crud/fast-crud';

import { ref } from 'vue';

import { isEmptyOrUnDef } from '@vben/utils';

import { DefUserApi } from '#/api/devOperation/tenant/defUser';
import { createdTimeColumn, indexColumn } from '#/plugins/fast-crud/common';

export function createCrudOptions(
  props: CreateCrudOptionsProps,
): CreateCrudOptionsRet {
  const selectedRowKeys = ref<string[]>([]);

  const { getSearchRef } = props.crudExpose;

  const validateSearch = async (
    _: any,
    _value: string,
    callback: (error?: Error | string) => void,
  ) => {
    const formData = getSearchRef().formData;
    if (
      isEmptyOrUnDef(formData.username) &&
      isEmptyOrUnDef(formData.email) &&
      isEmptyOrUnDef(formData.idCard) &&
      isEmptyOrUnDef(formData.mobile)
    ) {
      throw new Error('至少填写一个参数');
    }
    return callback();
  };

  return {
    crudOptions: {
      request: {
        pageRequest: DefUserApi.pageRequest,
      },
      actionbar: { show: false },
      toolbar: { show: false },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
            props.context.selectedRowKeys = changed;
          },
        },
      },
      search: {
        options: {
          // 显示校验错误信息
          showFeedback: true,
        },
        // 开启校验
        validate: true,
      },
      rowHandle: { show: false },
      columns: {
        ...indexColumn(props.crudExpose),
        username: {
          title: '用户名',
          type: 'text',
          search: {
            show: true,
            rules: [
              {
                validator: validateSearch,
                message: '至少填写一个参数',
                trigger: 'blur',
              },
            ],
          },
        },
        nickName: {
          title: '昵称',
          type: 'text',
          search: { show: false },
          column: { show: true },
        },
        email: {
          title: '邮箱',
          type: 'text',
          search: {
            show: true,
            rules: [{ validator: validateSearch, trigger: 'blur' }],
          },
        },
        idCard: {
          title: '身份证',
          type: 'text',
          search: {
            show: true,
            rules: [{ validator: validateSearch, trigger: 'blur' }],
          },
        },
        mobile: {
          title: '手机',
          type: 'text',
          search: {
            show: true,
            rules: [{ validator: validateSearch, trigger: 'blur' }],
          },
        },
        ...createdTimeColumn({ searchShow: false }),
      },
    },
  };
}

export const frontRules = () => {
  return {};
};
